<template>
<div class="app-container" element-loading-text="视频上传中..." element-loading-spinner="el-icon-loading" v-loading="uploadLoading">
  <div style="width: 920px">
    <el-form ref="form" :rules="rules" :model="form" label-width="120px">
      <el-form-item label="课程名称" prop="name">
        <el-input size="small" v-model="form.name" placeholder="请输入课程名称" />
      </el-form-item>
      <el-form-item label="课程描述" prop="des">
        <el-input type="textarea" :rows="5" size="small" v-model="form.des" placeholder="请输入课程描述" />
      </el-form-item>
      <el-form-item label="课程海报" required>
        <div style="color:#999">
          建议尺寸714*344px或2：1，JPG、PNG格式， 图片小于5M。
        </div>
        <el-upload
          :class="uploadUrl!=''?'hiddenUpload':''"
          action="https://service.bairicun.com/file/upload"
          list-type="picture-card"
          :on-success="handleSuccess"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item label="课程视频" required>
        <div style="color:#999">
          请上传MP4格式视频文件
        </div>
        <el-upload
          action="https://up-z2.qiniup.com"
          :data="qnObj"
          :show-file-list="false"
          :on-success="successUploadVideo"
          :before-upload="beforeUploadVideo">
          <el-button size="small" type="primary">上传视频</el-button>
        </el-upload>
        <div v-if="videoUrl" style="width:400px;height:200px;margin-top:20px;position:relative;border:1px solid #eee;">
          <video :src="videoUrl" controls style="width:400px;height:200px;"></video>
          <i style="position:absolute;top:-10px;right:-10px;font-size:30px;cursor:pointer;" @click="deleteVideo" class="el-icon-circle-close"></i>
        </div>
      </el-form-item>
      <el-form-item label="主讲教师" prop="teacherId">
        <el-select style="width:100%;" clearable size="small" v-model="form.teacherId" placeholder="请选择主讲教师">
          <el-option
            v-for="(item,index) in teacherList"
            :key="index"
            :label="item.realName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择试卷">
        <div style="display:flex;align-items:center;">
          <div style="margin-right:10px;">
            <span>
              练习试卷
            </span>
            <el-select clearable size="small" v-model="form.testId" placeholder="请选择练习试卷">
              <el-option
                v-for="(item,index) in testList"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </div>
          <div style="margin-right:10px;">
            <span>
              作业试卷
            </span>
            <el-select clearable size="small" v-model="form.taskId" placeholder="请选择作业试卷">
              <el-option
                v-for="(item,index) in taskList"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </div>
          <div style="margin-right:10px;">
            <span>
              考试试卷
            </span>
            <el-select clearable size="small" v-model="form.examId" placeholder="请选择考试试卷">
              <el-option
                v-for="(item,index) in examList"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </div>
        </div>
      </el-form-item>
      <!-- <el-form-item label="课程费用" prop="fee">
        <el-input size="small" v-model="form.fee" placeholder="请输入费用" />
      </el-form-item> -->
      <el-form-item>
        <el-button size="small" type="primary" @click="onSubmit('form')">保存</el-button>
        <el-button size="small" @click="onCancel">取消</el-button>
      </el-form-item>
    </el-form>

    <el-dialog title="选择课程课程" :visible.sync="modalVisible">
      <div style="display:flex;align-items: center;justify-content: space-between;margin:0 0 10px;">
        <div style="display:flex;align-items: center;">
          <el-form :inline="true" class="demo-form-inline">
            <el-form-item label="课程名称">
              <el-input clearable size="small" v-model="formInline.title" placeholder="标题"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button size="small" type="primary" @click="onSubmit">搜索</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <el-table @row-click="chooseone" ref="multipleTable" v-loading="listLoading" :data="tableList" element-loading-text="Loading" border fit highlight-current-row empty-text="暂无数据">
        <el-table-column label="选择" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-radio v-model="radio" :label="scope.row.id">
              <span class="el-radio__label"></span>
            </el-radio>
          </template>
        </el-table-column>
        <el-table-column label="ID" width="150">
          <template slot-scope="scope">
            {{ scope.row.id }}
          </template>
        </el-table-column>
        <el-table-column label="课程名称" width="200">
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column label="费用" width="200">
          <template slot-scope="scope">
            {{ scope.row.fee?scope.row.fee:'免费' }}
          </template>
        </el-table-column>
      </el-table>

      <div style="margin:10px 0 0 0;text-align:right;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="1"
          :page-sizes="[10, 30, 50, 100]"
          :page-size="1"
          layout="total, sizes, prev, pager, next, jumper"
          :total="0">
        </el-pagination>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="modalVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="modalVisible = false">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import {
  saveApi
} from '@/api/course'
import {
  getListApi
} from '@/api/teachers'
import {
  getQnTokenApi,
  getQnFileApi
} from '@/api/common'
import {
  getListPaperApi
} from '@/api/paper'

export default {
  components: {Tinymce},
  data() {
    return {
      uploadLoading: false,
      radio: '',
      tableList: [],
      listLoading: false,
      formInline: {
        title: ''
      },
      form: {
        name: '',
        des: '',
        teacherId: '',
        testId: '',
        taskId: '',
        examId: '',
      },
      rules: {
        name: [{
          required: true,
          message: '请输入标题',
          trigger: 'blur'
        }, ],
        des: [{
          required: true,
          message: '请输入描述',
          trigger: 'blur'
        }, ],
        teacherId: [{
          required: false,
          message: '请选择主讲教师',
          trigger: 'change'
        }, ],
      },
      dialogImageUrl: '',
      dialogVisible: false,
      uploadStatus: false,
      uploadUrl: '',
      uploadImgId: '',
      modalVisible: false,
      qnObj: {
        token: '',
        key: ''
      },
      fileKey: '',
      teacherList: [],
      videoId: '',
      videoUrl: '',
      testList: [],
      taskList: [],
      examList: [],
    }
  },
  mounted() {
    this.getQnToken()
    this.getTeachers()
    this.getTestList()
    this.getTaskList()
    this.getExamList()
  },
  methods: {
    getTestList() {
      getListPaperApi({
        pageSize: 1000,
        pageNum: 1,
        type: 1,
      }).then((res) => {
        this.testList = res.data.result.map((item) => {
          return {
            value: item.id,
            label: item.paperName
          }
        })
      })
    },
    getTaskList() {
      getListPaperApi({
        pageSize: 1000,
        pageNum: 1,
        type: 0,
      }).then((res) => {
        this.taskList = res.data.result.map((item) => {
          return {
            value: item.id,
            label: item.paperName
          }
        })
      })
    },
    getExamList() {
      getListPaperApi({
        pageSize: 1000,
        pageNum: 1,
        type: 2,
      }).then((res) => {
        this.examList = res.data.result.map((item) => {
          return {
            value: item.id,
            label: item.paperName
          }
        })
      })
    },
    deleteVideo() {
      this.videoId = ''
      this.videoUrl = ''
    },
    getTeachers() {
      getListApi({
        pageSize: 1000,
        pageNum: 1,
        state: 1,
      }).then((res) => {
        this.teacherList = res.data.result
      })
    },
    getQnToken() {
      getQnTokenApi().then((res) => {
        this.qnObj.token = res.data
      })
    },
    beforeUploadVideo(file) {
      this.uploadLoading = true
      let time = new Date()
      this.qnObj.key = `${String(time.getTime())}${file.name}`
      const isMP4 = file.type == "video/mp4"
      if (!isMP4) {
        this.$message.error("只能上传MP4格式视频!");
      }
      return isMP4
    },
    successUploadVideo(e) {
      console.log(e)
      this.uploadLoading = false
      this.fileKey = e.key
      this.getVideo()
    },
    getVideo() {
      getQnFileApi({
        fileToken: this.fileKey
      }).then((res) => {
        this.videoId = res.data.id
        this.videoUrl = res.data.url
      })
    },
    handleSizeChange() {

    },
    handleCurrentChange() {

    },
    chooseone(row){
      this.radio = row.id
    },
    handleRemove(file, fileList) {
      this.uploadUrl = ''
      this.uploadImgId = ''
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleSuccess(e) {
      if(e.code == 200) {
        this.uploadStatus = true
        this.uploadUrl = e.data.url
        this.uploadImgId = e.data.id
      }
    },
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.uploadImgId == '') {
            this.$message.error('请上传课程海报！');
            return
          }
          if(this.videoId == '') {
            this.$message.error('请上传课程视频！');
            return
          }
          saveApi({
            name: this.form.name,
            des: this.form.des,
            coverId: this.uploadImgId,
            videoId: this.videoId,
            exercisePaperId: this.form.testId,
            workPaperId: this.form.taskId,
            examPaperId: this.form.examId,
            teacherIds: this.form.teacherId
          }).then((res) => {
            this.$message.success('操作成功！');
            setTimeout(() => {
              this.$router.back(-1)
            }, 1000);
          })
        } else {
          return false;
        }
      });
    },
    onCancel() {
      this.$router.back(-1)
    },
    openke() {
      this.modalVisible = true
    }
  }
}
</script>
<style>
  .hiddenUpload .el-upload--picture-card{
    display:none !important;
  }
</style>
<style scoped>
.line {
  text-align: center;
}
</style>
